package manager

import (
	"center-platform/internal/event"
	"center-platform/internal/event/post"
	"center-platform/internal/event/user"
	"fmt"
)

type Manager struct {
	Listeners map[string][]event.Listener
}

var EventManager *Manager

func NewEventManager() {
	EventManager = &Manager{Listeners: make(map[string][]event.Listener)}
}

// AddListener 注册监听器
func (m *Manager) AddListener(eventType string, listener event.Listener) {
	m.Listeners[eventType] = append(m.Listeners[eventType], listener)
}

// RemoveListener 删除监听器
func (m *Manager) RemoveListener(eventType string, listenerToRemove event.Listener) {
	if _, ok := m.Listeners[eventType]; ok {
		for i, listener := range m.Listeners[eventType] {
			if listener == listenerToRemove {
				m.Listeners[eventType] = append(m.Listeners[eventType][:i], m.Listeners[eventType][i+1:]...)
				break
			}
		}
	}
}

// TriggerEvent 触发事件
func (m *Manager) TriggerEvent(eventType string, data string) {
	if listeners, ok := m.Listeners[eventType]; ok {
		for _, listener := range listeners {
			listener.HandleFunc(data)
		}
	}
}

func (m *Manager) Register() {
	module := map[string]func() map[string][]event.Listener{
		"user": user.GetEventListener,
		"post": post.GetEventListener,
	}

	for _, getListeners := range module {
		listeners := getListeners()
		for eventType, listenerList := range listeners {
			for _, val := range listenerList {
				m.AddListener(eventType, val)
			}
		}
	}
	fmt.Println("--------监听器加载成功-------")
}
